package com.zhuhjay.common.web.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.zhuhjay.common.base.exception.BasicBusinessException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件工具类
 * @author ZhuHJay
 * @date 2023/2/4 21:50
 */
public class FileUtils {

    /** 常见图片类型后缀 **/
    private static final String[] IMAGE_SUFFERS = {
            "BMP", "JPG", "JPEG", "PNG", "GIF"
    };

    /**
     * 检查文件的类型是否是图片类型
     * @param file 文件信息
     */
    public static void checkFileIsImage(MultipartFile file) {
        if (isEmpty(file)) {
            throw new BasicBusinessException("上传文件不能为空");
        }
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new BasicBusinessException("文件上传失败");
        }
        // 获取文件类型
        String fileSuf = FileUtil.extName(filename);
        for (String suffer : IMAGE_SUFFERS) {
            if (suffer.equalsIgnoreCase(fileSuf)) {
                return;
            }
        }
        throw new BasicBusinessException("文件类型错误");
    }

    /**
     * 生成文件名，格式 uuid.ext
     * @param originalFilename 文件原始名称
     * @return 文件名
     */
    public static String generateFileName(String originalFilename) {
        return IdUtil.fastSimpleUUID() + '.' + FileUtil.extName(originalFilename);
    }

    public static boolean isEmpty(MultipartFile file) {
        return file == null || file.isEmpty();
    }

    /**
     * 兼容浏览器响应头Content-Disposition的filename编码
     * @param request 请求
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String encodeFileName(HttpServletRequest request, String fileName) {
        final String firefox = "Firefox";
        // 兼容浏览器响应头Content-Disposition的filename编码
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains(firefox)) {
            return new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        return URLEncoder.encode(fileName, StandardCharsets.UTF_8);
    }

}
